/*
 * Copyright 2012-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codestd.security.shiro.filter;

import com.codestd.security.base.ResponseBean;
import com.codestd.security.model.SysUser;
import com.codestd.security.shiro.ResponseUtils;
import com.codestd.security.shiro.jwt.JwtTokenManager;
import com.codestd.security.shiro.jwt.MobileTokenManager;
import com.codestd.security.shiro.token.StatelessToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 处理Token
 *
 * @author Wang Chengwei(Jaune)
 * @since 1.0.0
 */
public class StatelessAuthenticationFilter extends FormAuthenticationFilter {

    private JwtTokenManager tokenManager;

    private MobileTokenManager mobileTokenManager;

    public JwtTokenManager getTokenManager() {
        return tokenManager;
    }

    public void setTokenManager(JwtTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public MobileTokenManager getMobileTokenManager() {
        return mobileTokenManager;
    }

    public void setMobileTokenManager(MobileTokenManager mobileTokenManager) {
        this.mobileTokenManager = mobileTokenManager;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            }
        }
        // 这里不需要跳转了，直接返回错误信息即可。
        ResponseUtils.printAccessDeniedError(response);
        // 阻止过滤器继续执行
        return false;
    }

    /**
     * 这里根据type字段判断是否为移动端，实际项目中可以使用spring-mobile
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String refreshToken = request.getParameter("refreshToken");
        String type = request.getParameter("type");
        if (refreshToken != null && type != null) {
            return new StatelessToken(refreshToken, type);
        }
        if (type != null) {
            StatelessToken token = new StatelessToken(null, type);
            token.setUsername(getUsername(request));
            token.setPassword(getPassword(request).toCharArray());
            token.setHost(getHost(request));
            token.setRememberMe(isRememberMe(request));
            return token;
        }
        return super.createToken(request, response);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        if (token instanceof StatelessToken) {
            return refreshTokenLoginHandle(token, subject, response);
        } else {
            JwtTokenManager jwtTokenManager = this.getTokenManager();
            SysUser user = (SysUser) subject.getPrincipals().getPrimaryPrincipal();
            String jwtToken = jwtTokenManager.createToken(user);
            ResponseUtils.printResponseBean(response, ResponseBean.mapBuilder()
                    .add("accessToken", jwtToken)
                    .success(true).status(200).build());
            // 登录成功，阻止过滤器链继续执行，并返回Token。
            return false;
        }
    }

    /**
     * refreshToken登录流程。
     */
    private boolean refreshTokenLoginHandle(AuthenticationToken token, Subject subject, ServletResponse response) {
        StatelessToken statelessToken = (StatelessToken) token;
        SysUser user = (SysUser) subject.getPrincipals().getPrimaryPrincipal();
        // 这里只要登录成功，就删除refreshToken并重新生成一个。注意这里是根据设备类型来删除的，也就是说同一个设备类型同一个用户只能有一个有效的refreshToken
        this.getMobileTokenManager().deleteRefreshToken(user.getUserId(), statelessToken.getType());

        // 创建refreshToken和accessToken并返回到前端
        String accessToken = this.getTokenManager().createTokenForMobile(user);
        String refreshToken = this.getMobileTokenManager().createRefreshToken(user, statelessToken.getType());
        ResponseUtils.printResponseBean(response, ResponseBean.mapBuilder()
                .add("accessToken", accessToken)
                .add("refreshToken", refreshToken)
                .success(true).status(200).build());
        // 登录成功，阻止过滤器链继续执行，并返回Token。
        return false;

    }

}
